package com.dcm.common.advice;


import com.dcm.common.annotation.EnableResponseBodyAdvice;
import com.dcm.common.annotation.IgnoreResponseBodyAdvice;
import com.dcm.common.constant.Constants;
import com.dcm.common.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author pengrongsheng
 **/
@Slf4j
@RestControllerAdvice(annotations = EnableResponseBodyAdvice.class)
public class CommonResponseAdvice implements ResponseBodyAdvice<Object> {


    /**
     * 是否请求包含了 包装注解 没有就直接返回 不需要重写返回体
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        log.info("returnType:" + returnType);
        log.info("converterType:" + converterType);
        return !returnType.getDeclaringClass().isAnnotationPresent(IgnoreResponseBodyAdvice.class) && !returnType.getMethod().isAnnotationPresent(IgnoreResponseBodyAdvice.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        log.info("进入 返回体 重写响应的格式》》》处理中。。。");
        // 判断响应的Content-Type为JSON格式的body
        if (MediaType.APPLICATION_JSON.equals(selectedContentType)) {
            // 如果响应返回的对象为统一响应体，则直接返回body
            if (body instanceof CommonResponse) {
                return body;
            } else {
                // 只有正常返回的结果才会进入这个判断流程，返回正常成功的状态码+信息+数据。
                CommonResponse responseResult = new CommonResponse(0, Constants.ResponseMsg.SUCCESS, body);
                return responseResult;
            }
        }
        return body;
    }
}
